package com.sinosun.autotestmachine.tools.proxy;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.sinosun.autotestmachine.App;
import com.sinosun.autotestmachine.tools.TaskManager;
import com.sinosun.autotestmachine.tools.ValueInfo;
import com.sinosun.autotestmachine.tools.ValueType;
import com.sinosun.autotestmachine.tools.Collector.Cache;
import com.sinosun.autotestmachine.tools.Collector.MsgListenerCollector;
import com.sinosun.autotestmachine.tools.Collector.MsgSendCollector;
import com.sinosun.autotestmachine.tools.parser.ContentMaker;
import com.sinosun.autotestmachine.tools.parser.ParamKey;
import com.sinosun.autotestmachine.tools.proxy.callback.CallbackWrapper;
import com.sinosun.autotestmachine.tools.utils.Utils;
import com.sinosun.mstplib.MstpClient;
import com.sinosun.mstplib.MstpException;
import com.sinosun.mstplib.message.Message;

import android.text.TextUtils;
import android.util.Log;

public class MessageModule {
	protected static int syncSendMessage(MstpClient mstpClient, String paramJson, String cacheParam) {
		List<String> params = new ArrayList<String>();		//保存所有的消息内容
		List<String> cacheParams = new ArrayList<String>();
		try {
			JSONObject jo = new JSONObject(paramJson);
			if(jo.has(ParamKey.MESSAGR_CONTENT_ID)) {
				JSONArray jsonArr = jo.getJSONArray(ParamKey.MESSAGR_CONTENT_ID);
				for (int i = 0; i < jsonArr.length(); i++) {
					ValueInfo value = Utils.getMsgRealInfo(jsonArr.getString(i));
					if (value.getValueType() == ValueType.INDEX) {
						String tmp = App.getTestConfig().getMsgContent().get(value.getValueContent());
						params.add(tmp);
					} else {
						params.add(jsonArr.getString(i));
					}
				}
			} else {
				return ErrorCode.ERR_PARAM_ERROR;
			}
			
			if (cacheParam != null) {
				JSONObject cacheJo = new JSONObject(cacheParam);
				if (cacheJo.has(ParamKey.SEND_MESSAGE_ID)) {
					JSONArray cacheArr = cacheJo.getJSONArray(ParamKey.SEND_MESSAGE_ID);
					for (int i = 0; i < cacheArr.length(); i++) {
						cacheParams.add(cacheArr.getString(i));
					}
				} else {
					return ErrorCode.ERR_PARAM_ERROR;
				}
				
				if (cacheParams.size() <= 0) {
					return ErrorCode.ERR_PARAM_ERROR;
				}
			}
		} catch (JSONException e1) {
			e1.printStackTrace();
			return ErrorCode.ERR_PARAM_ERROR;
		}
		
		if (params.size() <= 0) {
			return ErrorCode.ERR_PARAM_ERROR;
		}
		
		try {
			MsgSendCollector collector = new MsgSendCollector();
			for (String content : params) {	//遍历发送所有的数据
				Log.e("XXX", "content:" + content);
				Message m = ContentMaker.makeMessage(content, mstpClient.getMstpId());
				String messageId = mstpClient.sendMessage(m);
				m.setMsgId(messageId);
				collector.addMessageID(m);
			}
			
			CallbackWrapper.makeMessageSendCallback(collector);		//设置监听
			collector.waitResult();		//阻塞等待处理结果
			CallbackWrapper.clearMessageSendCallback();
			for (int i = 0; i < cacheParams.size(); i++) {
				Cache.messageSendCache.put(cacheParams.get(i), collector.getMessageIDs().get(i));
			}
			return collector.getResult();
		} catch (JSONException e) {
			e.printStackTrace();
			return ErrorCode.ERR_PARAM_ERROR;
		} catch (MstpException e) {
			e.printStackTrace();
			return e.getErrorCode();
		} catch (InterruptedException e) {
			e.printStackTrace();
			return ErrorCode.ERR_UNEXPECT_RESULT;
		}
	}
	
	
	protected static int verifyRecvMessage(MstpClient mstpClient, String paramJson) {
		List<Message> params = new ArrayList<Message>();		//保存所有的消息内容
		try {
			JSONObject jo = new JSONObject(paramJson);
			if(jo.has(ParamKey.VERIFY_MSGID)) {
				JSONArray jsonArr = jo.getJSONArray(ParamKey.VERIFY_MSGID);
				for (int i = 0; i < jsonArr.length(); i++) {
					params.add(Cache.messageSendCache.get(jsonArr.getString(i)));
				}
			} else {
				return ErrorCode.ERR_PARAM_ERROR;
			}
		} catch (JSONException e1) {
			e1.printStackTrace();
			return ErrorCode.ERR_PARAM_ERROR;
		}
		
		if (params.size() <= 0) {
			return ErrorCode.ERR_PARAM_ERROR;
		}
		MsgListenerCollector collector = new MsgListenerCollector();
		for (Message ele : params) {
			collector.addKeyIntoList(ele);
		}
		collector.setResult(ErrorCode.ERR_TIMEOUT_ERROR);
		CallbackWrapper.makeMessageReceiveListener(collector);
		try {
			collector.waitResult(TaskManager.getTaskManager().getWaitTimeSec());
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		CallbackWrapper.clearMessageListener();
		return collector.getResult();
	}
	
	protected static int sendHaveReadMessage(MstpClient mstpClient, String paramJson) {
		List<String> params = new ArrayList<String>();		//保存所有的消息内容
		String mstpId = new String("");
		try {
			JSONObject jo = new JSONObject(paramJson);
			if(jo.has(ParamKey.SHOULD_READ_MSG_ID)) {
				JSONArray jsonArr = jo.getJSONArray(ParamKey.SHOULD_READ_MSG_ID);
				for (int i = 0; i < jsonArr.length(); i++) {
					String tmp = jsonArr.getString(i);
					ValueInfo vi  = Utils.getSendRealInfo(tmp);
					if (vi.getValueType() == ValueType.INDEX) {
						params.add(Cache.messageSendCache.get(tmp).getMsgId());
					} else {
						params.add(tmp);
					}
				}
			} else {
				return ErrorCode.ERR_PARAM_ERROR;
			}
			if (jo.has(ParamKey.MSTPID)) {
				mstpId = jo.getString(ParamKey.MSTPID);
				ValueInfo value = Utils.getUserRealInfo(mstpId);
				if (value.getValueType() == ValueType.INDEX) {		// value 数据内容符合匹配规则，从内存中取出对应的 mstpId
					mstpId = App.getTestConfig().getUsers().get(value.getValueContent());
					if (TextUtils.isEmpty(mstpId)) {
						return ErrorCode.ERR_PARAM_ERROR;
					}
				}
			}
		} catch (JSONException e1) {
			e1.printStackTrace();
			return ErrorCode.ERR_PARAM_ERROR;
		}
		
		if (params.size() <= 0) {
			return ErrorCode.ERR_PARAM_ERROR;
		}
		
		try {
			Log.e("XXX", "params : " + params);
			Log.e("XXX", "mstpId : " + mstpId);
			String msgId = mstpClient.haveReadMessage(params, mstpId);
			MsgSendCollector collector = new MsgSendCollector();
			Message m = new Message();
			m.setMsgId(msgId);
			collector.addMessageID(m);
			CallbackWrapper.makeMessageSendCallback(collector);		//设置监听
			collector.waitResult();		//阻塞等待处理结果
			CallbackWrapper.clearMessageSendCallback();
			return collector.getResult();
		} catch (MstpException e) {
			e.printStackTrace();
			return e.getErrorCode();
		} catch (InterruptedException e) {
			e.printStackTrace();
			return ErrorCode.ERR_UNEXPECT_RESULT;
		}
	}
	
	protected static int sendRevokeMessage(MstpClient mstpClient, String paramJson) {
		List<String> params = new ArrayList<String>();		//保存所有的消息内容
		String mstpId = new String("");
		try {
			JSONObject jo = new JSONObject(paramJson);
			if(jo.has(ParamKey.SHOULD_REVOKE_MSG_ID)) {
				JSONArray jsonArr = jo.getJSONArray(ParamKey.SHOULD_REVOKE_MSG_ID);
				for (int i = 0; i < jsonArr.length(); i++) {
					String tmp = jsonArr.getString(i);
					ValueInfo vi  = Utils.getSendRealInfo(tmp);
					if (vi.getValueType() == ValueType.INDEX) {
						params.add(Cache.messageSendCache.get(tmp).getMsgId());
					} else {
						params.add(tmp);
					}
				}
			} else {
				return ErrorCode.ERR_PARAM_ERROR;
			}
			if (jo.has(ParamKey.MSTPID)) {
				mstpId = jo.getString(ParamKey.MSTPID);
				ValueInfo value = Utils.getUserRealInfo(mstpId);
				if (value.getValueType() == ValueType.INDEX) {		// value 数据内容符合匹配规则，从内存中取出对应的 mstpId
					mstpId = App.getTestConfig().getUsers().get(value.getValueContent());
					if (TextUtils.isEmpty(mstpId)) {
						return ErrorCode.ERR_PARAM_ERROR;
					}
				}
			}
		} catch (JSONException e1) {
			e1.printStackTrace();
			return ErrorCode.ERR_PARAM_ERROR;
		}
		
		if (params.size() <= 0) {
			return ErrorCode.ERR_PARAM_ERROR;
		}
		
		try {
			int ret = ErrorCode.SUCCESS;
			for (String param : params) {
				String msgId = mstpClient.revokeMessage(param, mstpId);
				MsgSendCollector collector = new MsgSendCollector();
				Message m = new Message();
				m.setMsgId(msgId);
				collector.addMessageID(m);
				CallbackWrapper.makeMessageSendCallback(collector);		//设置监听
				collector.waitResult();		//阻塞等待处理结果
				CallbackWrapper.clearMessageSendCallback();
				ret = collector.getResult();
				if (ret != ErrorCode.SUCCESS) {
					return ret;
				}
			}
			return ret;
		} catch (MstpException e) {
			e.printStackTrace();
			return e.getErrorCode();
		} catch (InterruptedException e) {
			e.printStackTrace();
			return ErrorCode.ERR_UNEXPECT_RESULT;
		}
	}
	
	protected static int verifyHaveReadMessage(MstpClient mstpClient, String paramJson) {
		List<Message> params = new ArrayList<Message>();		//保存所有的消息内容
		try {
			JSONObject jo = new JSONObject(paramJson);
			if(jo.has(ParamKey.VERIFY_MSGID)) {
				JSONArray jsonArr = jo.getJSONArray(ParamKey.VERIFY_MSGID);
				for (int i = 0; i < jsonArr.length(); i++) {
					String tmp = jsonArr.getString(i);
					ValueInfo vi = Utils.getNodeIDRealInfo(tmp);
					if (vi.getValueType() == ValueType.INDEX) {
						tmp = Cache.messageSendCache.get(tmp).getMsgId();
					}
					Message m = new Message();
					m.setMsgId(tmp);
					params.add(m);
				}
			} else {
				return ErrorCode.ERR_PARAM_ERROR;
			}
		} catch (JSONException e1) {
			e1.printStackTrace();
			return ErrorCode.ERR_PARAM_ERROR;
		}
		
		if (params.size() <= 0) {
			return ErrorCode.ERR_PARAM_ERROR;
		}
		
		MsgListenerCollector collector = new MsgListenerCollector();
		for (Message ele : params) {
			collector.addKeyIntoList(ele);
		}
		collector.setResult(ErrorCode.ERR_TIMEOUT_ERROR);
		CallbackWrapper.makeHaveReadListener(collector);
		try {
			collector.waitResult(TaskManager.getTaskManager().getWaitTimeSec());
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		CallbackWrapper.clearHaveReadListener();
		return collector.getResult();
	}
	
	protected static int verifyRevokeMessage(MstpClient mstpClient, String paramJson) {
		List<Message> params = new ArrayList<Message>();		//保存所有的消息内容
		try {
			JSONObject jo = new JSONObject(paramJson);
			if(jo.has(ParamKey.VERIFY_MSGID)) {
				JSONArray jsonArr = jo.getJSONArray(ParamKey.VERIFY_MSGID);
				for (int i = 0; i < jsonArr.length(); i++) {
					String tmp = jsonArr.getString(i);
					ValueInfo vi = Utils.getNodeIDRealInfo(tmp);
					if (vi.getValueType() == ValueType.INDEX) {
						tmp = Cache.messageSendCache.get(tmp).getMsgId();
					}
					Message m = new Message();
					m.setMsgId(tmp);
					params.add(m);
				}
			} else {
				return ErrorCode.ERR_PARAM_ERROR;
			}
		} catch (JSONException e1) {
			e1.printStackTrace();
			return ErrorCode.ERR_PARAM_ERROR;
		}
		
		if (params.size() <= 0) {
			return ErrorCode.ERR_PARAM_ERROR;
		}
		
		MsgListenerCollector collector = new MsgListenerCollector();
		for (Message ele : params) {
			collector.addKeyIntoList(ele);
		}
		collector.setResult(ErrorCode.ERR_TIMEOUT_ERROR);
		CallbackWrapper.makeRevokeListener(collector);
		try {
			collector.waitResult(TaskManager.getTaskManager().getWaitTimeSec());
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		CallbackWrapper.clearRevokeListener();
		return collector.getResult();
	}
}
